const parser = (sql,keywords, delimiters ) => {
    const delimiter = [";", "UNION"]
    // 移除注释
    sql = sql.replace(/--.*?\n|--.*$/gm, '').replace(/\/\*[\s\S]*?\*\//g, '');
    const quoteChar = "`";
    const splitChar = ".";
    let quoteCharFlag = false;
    const tokens = [];
    let arr = [];
    // 按照空格分隔SQL语句
    let parts = sql.split(/\s+/);
    // 逐个处理分隔后的部分
    for (let i = 0; i < parts.length; i++) {
        let part = parts[i];
         let next = parts[i+1];
        if (delimiter.indexOf(part.toUpperCase())!=-1) {
            if (arr.length > 0)  tokens.push(arr);
           arr=[];
            if (part.toUpperCase() === "UNION" && next && next.toUpperCase() === "ALL") {
                i++;
            }
           continue;
        }
        let temp = parserToken(part)
        for(let t of temp){
             if (delimiter.indexOf(part.toUpperCase()) != -1) {
                if (arr.length > 0)  tokens.push(arr);
                arr=[];
                if (part.toUpperCase() === "UNION" && next && next.toUpperCase() === "ALL") {
                	i++;
                }
                continue;
             }
             arr.push(t);
        }
    }
    if (arr.length > 0) {
        tokens.push(arr);
    }
    if (tokens.length === 0) {
        tokens.push([sql]);
    }
    return tokens;
}


const parserToken = (token) => {
    const quoteChar = "`";
    const splitChar = ",";
    const delimiter = ";"
    let quoteCharFlag = false;
    const stringArray = [];
    let arr = [];
    for (let i of token) {
        if (i === quoteChar) {
            if (quoteCharFlag) {
                quoteCharFlag = false;
            } else {
                quoteCharFlag = true;
            }
            continue;
        }
        if ((i === splitChar) && !quoteCharFlag) {
            if (arr.length > 0) stringArray.push(arr.join(""));
            arr = [];
            continue;
        }
        if ((i === delimiter) && !quoteCharFlag) {
            if (arr.length > 0) stringArray.push(arr.join(""));
            stringArray.push(i);
            arr = [];
            continue;
        }
        arr.push(i);
    }
    if (arr.length > 0) {
        stringArray.push(arr.join(""));
    }
    if (stringArray.length === 0) {
        stringArray.push(token);
    }
    return stringArray;
}


export default parser